package com.nulldev.util.web.dns.server.server.engine;

import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.dns.server.message.DNSMessageOverlay;
import com.nulldev.util.web.dns.server.message.DNSQuestion;
import com.nulldev.util.web.dns.server.message.DNSRecord;
import com.nulldev.util.web.dns.server.message.DNSResponseBuilder;
import com.nulldev.util.web.dns.server.message.DNSResponseCode;
import com.nulldev.util.web.dns.server.server.DNSPayload;

public class SingleTubeEngine implements DNSEngine {
	private final Logger logger = LoggerFactory.getLogger(SingleTubeEngine.class);

    /**
     * Answers every question with the same response.
     * @param payload Query
     * @return Response
     */
    @Override
    public DNSPayload processDnsPayload(DNSPayload payload) {
        DNSResponseBuilder builder = new DNSResponseBuilder(payload.getMessageData());
        builder.setAuthoritativeAnswer(true)
                .setRecursionAvailable(true)
                .setResponseCode(DNSResponseCode.NO_ERROR);

        DNSMessageOverlay overlay = new DNSMessageOverlay(payload.getMessageData());
        DNSQuestion[] questions = overlay.getQuestions();
        byte[] answer = new byte[] { 64, 65, 66, 67 };
        for (DNSQuestion question: questions) {
            builder.addAnswer(new DNSRecord(question.getQuestionName(), question.getQuestionType(),
                    question.getQuestionClass(), 120, answer));
        }
        payload.setMessageData(builder.build());
        logger.debug("Returning DNS answer {}", answer);
        return payload;
    }
}
